import React, { useEffect, useState } from "react";
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { LOGIN_USER_STATE_REQ_FAIL, LOGIN_USER_STATE_REQ_SUCCESS, cleanUserState, getUserState } from "@/store/actions/userState";
import NavigateBar from "@/components/NavigateBar";
import icon_home_garid from '@/assets/icon_home_garid.png'
import icon_home_increase1 from '@/assets/icon_home_increase1.png'
import icon_home_increase2 from '@/assets/icon_home_increase2.png'
import icon_home_increase3 from '@/assets/icon_home_increase3.png'
import icon_app_logo from '@/assets/icon_app_logo.png'
import icon_login_refuse from "@/assets/icon_login_refuse.png"
import { DotLoading, Mask, Slider } from "antd-mobile";
import { PageTag } from "@/utils/pageTag";
import { saveEvent } from "@/store/actions/saveEvent";
import { useFormik } from "formik";
import './loginAd.css';
import '../../App.css'
import '../Home/home.css'
import '../Proof/proof.css';
import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
import AddHomeEvent from "@/utils/addHomeEvent";
import { LOGIN_REQ_FAIL, LOGIN_REQ_SUCCESS, cleanLoginState, doLogin } from "@/store/actions/login";
import { SEND_OTP_REQ_FAIL, SEND_OTP_REQ_SUCCESS, cleanOtpState, sendOtp } from "@/store/actions/sendOtp";
import { removeUserInfo } from "@/utils/storage";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import OtpInput from "@/components/OtpInput";
import Input from "@/components/Input";
import SmartChat from "@/utils/smartChat";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import AppParams from "@/utils/appParams";




/**
 * 登录页-样式1
 */
export default function LoginAd() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add loginAd弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(false);

    //滑条值
    const [sliderValue, setSliderValue] = useState('6,000');

    //倒计时状态
    const [canStart, setCanStart] = useState(false);

    //需要转登录状态
    const [needToLoginPage, setNeedToLoginPage] = useState(false);

    //需要转注册状态
    const [needToRegisterPage, setNeedToRegisterPage] = useState(false);

    //按键文字
    const [isRegitsterType, setIsRegitsterType] = useState(false);

    //获取Redux Store中的信息
    const sendOtpInfo = useSelector(state => state.sendOtp)

    //获取Redux Store中的信息
    const loginInfo = useSelector(state => state.login)

    //获取Redux Store中的用户状态信息
    const userStateInfo = useSelector(state => state.userState)

    //router
    const history = useHistory()

    const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        //添加 fb 像素
        // eslint-disable-next-line no-undef
        fbq('trackCustom', 'Page_Login');
        // eslint-disable-next-line no-undef
        gtag('trackCustom', 'Page_Login');

        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //清除登录信息
        dispatch(cleanLoginState())
        dispatch(cleanUserState())
        dispatch(cleanOtpState())

        //来源
        const dreferrer = document.referrer || ""
        console.log("document.referrer:==========" + dreferrer)

        //来源参数
        const queryParams = new URLSearchParams(location.search);
        const isRegister = queryParams.get('isRegister') || ""
        if (isRegister === "YES") {
            setIsRegitsterType(true)
        } else {
            setIsRegitsterType(false)
        }

        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    //监听验证码接口返回
    useEffect(() => {
        console.log("Login-监听验证码返回")
        console.log(sendOtpInfo)
        //获取短信发送成功返回
        if (sendOtpInfo.status === SEND_OTP_REQ_SUCCESS) {
            console.log("Login-短信发送成功")
            console.log(sendOtpInfo)
            //关闭loading
            setMaskVisible(false)

            //开始倒计时
            setCanStart(true)

            const directLoginFlag = sendOtpInfo.directLoginFlag || ""
            if (directLoginFlag === "YES") {
                //验证手机号
                let mobile = form.values.mobile

                //验证验证码
                let code = "0000"

                //请求登录
                doOtpLogin(mobile, code, "YES")
            }

        } else if (sendOtpInfo.status === SEND_OTP_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)

            //判断弹框----暂时关闭
            const otpResCode = sendOtpInfo.resCode || -1
            if (otpResCode === 2001) {
                //需要弹提示--你是新客，需要注册
                setNeedToRegisterPage(true)
                setNeedToLoginPage(false)

            } else if (otpResCode === 2002) {
                //需要弹提示--你是旧客，需要登录
                setNeedToRegisterPage(false)
                setNeedToLoginPage(true)
            }
        }
    }, [sendOtpInfo])

    //监听登录接口返回
    useEffect(() => {
        //获取短信发送成功返回
        if (loginInfo.status === LOGIN_REQ_SUCCESS) {
            console.log("Login-登录成功")
            console.log(loginInfo)
            //关闭loading
            setMaskVisible(false)

            // 设置salesmartly
            let mobile = form.values.mobile
            SmartChat.saveUserInfo(mobile);

            //查询用户状态
            getUserStateInfo()

        } else if (loginInfo.status === LOGIN_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [loginInfo])

    useEffect(() => {
        console.log("LOGIN-待等用户流程信息返回")
        console.log(userStateInfo)
        if (userStateInfo.status === LOGIN_USER_STATE_REQ_SUCCESS) {
            //关闭loading
            setMaskVisible(false)

            console.log("LOGIN-再次查询user state:")
            console.log("LOGIN-applyStatus: " + userStateInfo.applyStatus)
            console.log("LOGIN-orderStatus: " + userStateInfo.orderStatus)
            console.log("LOGIN-signFlag: " + userStateInfo.signFlag)
            console.log("Launch-signOrderId: " + userStateInfo.signOrderId)

            //是否为签约中
            const isHomeSigning = isLoanSigning(userStateInfo.signFlag, userStateInfo.signOrderId)
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(userStateInfo.applyStatus)
            //是否为拒绝
            const isHomeReject = isLoanReject(userStateInfo.applyStatus, userStateInfo.orderStatus)
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(userStateInfo.orderStatus)
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(userStateInfo.orderStatus)
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
            console.log("LOGIN-isHomeReviewing: " + isHomeReviewing)
            console.log("LOGIN-isHomeReject: " + isHomeReject)
            console.log("LOGIN-isHomeLoaning: " + isHomeLoaning)
            console.log("LOGIN-isHomeRepay: " + isHomeRepay)
            console.log("LOGIN-isHomeNotLoan: " + isHomeNotLoan)
            console.log("LOGIN-isHomeSigning: " + isHomeSigning)

            //页面转发
            setTimeout(() => {
                if (isHomeSigning) {
                    history.replace('/guide')
                } else if (isHomeReviewing) {
                    history.replace('/review')
                } else if (isHomeReject) {
                    history.replace('/reject')
                } else if (isHomeLoaning) {
                    history.replace('/loaning')
                } else if (isHomeRepay) {
                    history.replace('/repay')
                } else {
                    history.replace('/home')
                }
            }, 500)
        } else if (userStateInfo.status === LOGIN_USER_STATE_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [userStateInfo])

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            code: '',
            agreePrivacy: true
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            if (!values.mobile) {
                errors.mobile = "phone number can't be none"
            }
            if (!values.code) {
                errors.code = "otp can't be none"
            }
            if (!values.agreePrivacy) {
                errors.privacy = "read and agree pricayc policy"
            }

            return errors
        }
    })

    //获取用户流程信息
    const getUserStateInfo = () => {
        console.log("LOGIN-获取用户流程信息=====")
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserState(PageTag.LOGIN)

            //触发接口
            dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求短信接口
    const doSendOtp = async (mobile) => {
        console.log("doSendOtp: " + mobile);
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action -- 暂时关闭
            // const pageType = isRegitsterType ? "REGPAGE" : "LOGINPAGE"
            const pageType = ""
            const action = sendOtp(mobile, pageType)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doOtpLogin = async (mobile, code, directLoginFlag = "NO") => {
        console.log("doLogin: " + mobile + " , " + code);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = doLogin(mobile, code, directLoginFlag)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //点击获取otp
    const onSendSmsCode = async () => {
        //验证是否在倒计时中
        //打点
        doHitEvent("LOGIN_OTP_CLICK")

        //验证手机号
        let mobile = form.values.mobile
        if (mobile.length < 9) {
            form.setTouched({ mobile: true })
            return
        }

        //请求发送短信
        doSendOtp(mobile)
    }

    //点击登录
    const onLoginSubmit = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            //验证手机号
            let mobile = form.values.mobile

            //验证验证码
            let code = form.values.code

            //请求登录
            doOtpLogin(mobile, code, "NO")

        } catch (e) {
            console.log(e)
        }
    }

    // 转登录弹框--点击确定
    const onHandleToLoginPageMaskConfirm = () => {
        setNeedToRegisterPage(false)
        setNeedToLoginPage(false)
        history.goBack()
    }

    // 转注册弹框--点击确定
    const onHandleToRegisterPageMaskConfirm = () => {
        setNeedToRegisterPage(false)
        setNeedToLoginPage(false)
        history.goBack()
    }

    // 点击add loginAd监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add loginAd监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add loginAd
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add loginAd监听`)
        setAddHomeMaskVisible(false)
    }

    //滑条值变化监听
    const onHandleSliderChnaged = (value) => {
        const startValue = 6000
        const edgeValue = (20000 - 6000)
        const curValue = startValue + (value * 1000)//(edgeValue * value / 100)
        const curValueStr = curValue + ""
        const start3Char = curValueStr.substring(0, curValueStr.length - 3)
        const last3Char = curValueStr.substring(curValueStr.length - 3)
        const result = start3Char + "," + last3Char
        setSliderValue(result);
    };

    return (
        <div className="loginAdRoot">
            <div className="loginAdRootTopContent">
                {/* 顶部背景 */}
                {/* <div className="loginAdTopBackground"> </div> */}

                <NavigateBar theme="transparent" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>Loan Station</NavigateBar>

                {/* 使用添加 loginAd screen bar */}
                {/* <AddFavorite theme="transparent" onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

                <div className="loginAdAmountContent loginAdMarginTop24Px">

                    <div className="loginAdTopCardContent">
                        <div className="loginAdTopCardContentLeft">
                            <div className="contentRowStart">
                                <img className="loginAdLogoImage" src={icon_app_logo} alt="" />
                                <div className="loginAdAmountTitle loginAdMarginTopNone">Loan</div>
                                <div className="loginAdAmountTitle loginAdTitleColorMain loginAdMarginTopNone"> Station</div>
                            </div>

                            <div className="loginAdAmountTips">{'Simple, fast and safe personal\ninstant loan service'}</div>

                            {/* <div className="loginAdBtnApplyContent">
                                <div className="loginAdBtnApply">Apply</div>
                            </div> */}
                        </div>

                        <div className="loginAdTopCardContentRight">
                            <img className="loginAdGaridImage" src={icon_home_garid} alt="" />
                        </div>
                    </div>

                    <div className="loginAdCardContent loginAdMarginTop24Px">
                        <div className="loginAdSliderContent">
                            <div className="contentRowStart">
                                <div className="loginAdSlideStartEdge"></div>
                                <div className="loginAdSliderTitle loginAdTitleFontBold">How much money do you need</div>
                            </div>

                            <div className="contentRowStart">
                                <div className="loginAdSlideAmountContent">
                                    <div className="loginAdSlideRowCenter">
                                        <div className="loginAdSliderTitle loginAdTitleFont12Px loginAdMarginRight4Px"> {AppParams.currency}</div>
                                        <div className="loginAdSliderTitle loginAdTitleFont24Px loginAdTitleFontBold">{sliderValue}</div>
                                    </div>
                                    <div className="loginAdSliderTitle loginAdTitleFont12Px loginAdTitleColrTips loginAdTitleAlignCenter loginAdInsideTopEdge">Loan amount</div>
                                </div>

                                <div className="loginAdSlideAmountContent">
                                    <div className="loginAdSlideRowCenter">
                                        <div className="loginAdSliderTitle loginAdTitleFont24Px loginAdTitleColorWhite loginAdMarginRight4Px loginAdTitleFontBold">10%</div>
                                        <div className="loginAdSliderTitle loginAdTitleFont12Px">(par an)</div>
                                    </div>
                                    <div className="loginAdSliderTitle loginAdTitleFont12Px loginAdTitleColrTips loginAdTitleAlignCenter loginAdInsideTopEdge">Interest rate</div>
                                </div>
                            </div>

                            <div className="loginAdSlideRowTracker">
                                <div className="loginAdSlideRowTrackerSlider">
                                    <Slider min={0} max={14} defaultValue={0}
                                        style={{ '--fill-color': '#DCFF79' }}
                                        onChange={onHandleSliderChnaged}
                                    />
                                </div>

                                {/* <input className="loginAdSlideTracker" type="range" min={0} max={100} value={100} disabled /> */}
                            </div>

                            <div className="loginAdSlideRowAmountRange">
                                <div className="loginAdSlideMinAmount"> {AppParams.currency} 6,000</div>
                                <div className="loginAdSlideMaxAmount"> {AppParams.currency} 20,000</div>
                            </div>
                        </div>
                    </div>

                    <div className="loginAdCardContent loginAdMarginTop16Px">
                        <div className="loginAdSliderContent">
                            <div className="contentRowStart">
                                <div className="loginAdSlideStartEdge"></div>
                                <div className="loginAdSliderTitle loginAdTitleFontBold">Sign up to apply for your loan</div>
                            </div>

                            <form className="pageContentColumn loginAdMarginTop16Px loginAdPaddingHor14Px" onSubmit={form.handleSubmit}>
                                {/* 手机号码输入框 */}
                                <div className="loginAdVerifyInput">
                                    <Input
                                        isAdMode={true}
                                        title="Enter your mobile number"
                                        name="mobile"
                                        placeholder="Entrer"
                                        type="text"
                                        value={form.values.mobile}
                                        onBlur={form.handleBlur}
                                        onChange={form.handleChange}
                                        autoComplete="off" />
                                </div>
                                {form.errors.mobile && form.touched.mobile && (
                                    <div className="validate">{form.errors.mobile}</div>
                                )}

                                <div className="loginAdVerifyInput loginAdMarginTop14Px">
                                    {/* 验证码输入框 */}
                                    <OtpInput
                                        isAdMode={true}
                                        title="Please enter the verification code"
                                        name="code"
                                        placeholder="Entrer"
                                        maxLength={6}
                                        type="text"
                                        value={form.values.code}
                                        onChange={form.handleChange}
                                        onBlur={form.handleBlur}
                                        onClickCallback={onSendSmsCode}
                                        canStart={canStart}
                                        autoComplete="off" />
                                </div>
                                {form.errors.code && form.touched.code && (
                                    <div className="validate">{form.errors.code}</div>
                                )}
                            </form>

                            {/* 登录提交 */}
                            <div className="loginAdSubmitContent">
                                <div className="loginAdSubmit" onClick={form.handleSubmit}>Sign up</div>
                                {/* <div className={classNames('loginAdSubmit', (form.isValid && form.dirty) ? '' : 'loginAdSubmitBan disabled')} onClick={form.handleSubmit} disabled={true}>Sign up</div> */}
                            </div>

                            {/* privacy policy */}
                            <PrivacyPolicyLink pageTag={"LOGIN"} showCheckbox={false} linkText="Privacy policy" />

                        </div>
                    </div>
                </div>
            </div>

            <div className="contentColumnCenter loginAdRowTopEdge contentHorizontalPadding contentVerticalPadding">
                <div className="loginAdTitleRow">
                    {/* <img className="loginAdWhyChooseImage" src={icon_why_choose} alt="" /> */}
                    <span className="loginAdHeaderTitle loginAdTitleAlignCenter loginAdTitleFont20Px">{'Pourquoi choisir Loan Station'}</span>
                    {/* <img className="loginAdTitleImage" src={icon_home_arrow_right} alt="" /> */}
                </div>

                <div className="contentRowStart loginAdInsideTopEdge loginAdIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase1} alt="" />
                    <div className="loginAdIncreaseTextContent">
                        <span className="loginAdIncreaseTitle loginAdTitleColorIndex loginAdTitleFont18Px loginAdTitleFontBold">NO.1</span>
                        <span className="loginAdIncreaseTitle loginAdMarginTop9Px">High amount and reasonable interest.</span>
                    </div>
                </div>

                <div className="contentRowStart loginAdInsideTopEdge loginAdInsideTopEdge loginAdIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase2} alt="" />
                    <div className="loginAdIncreaseTextContent">
                        <span className="loginAdIncreaseTitle loginAdTitleColorIndex loginAdTitleFont18Px loginAdTitleFontBold">NO.2</span>
                        <span className="loginAdIncreaseTitle loginAdMarginTop9Px">{'No credit check ,no app, 3 minutes\nget loan.'}</span>
                    </div>
                </div>

                <div className="contentRowStart loginAdInsideTopEdge loginAdInsideTopEdge loginAdIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase3} alt="" />
                    <div className="loginAdIncreaseTextContent">
                        <span className="loginAdIncreaseTitle loginAdTitleColorIndex loginAdTitleFont18Px loginAdTitleFontBold">NO.3</span>
                        <span className="loginAdIncreaseTitle loginAdMarginTop9Px">{'With continuous use, loan amount\nincreases rapidly.'}</span>
                    </div>
                </div>
            </div>

            {/* add loginAd gif dialog */}
            <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} />


            {/* 转登录页弹框 */}
            <Mask visible={needToLoginPage} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="applyOverlayBg">
                    <div className="applyOverlayContent">
                        <div className="applyOverlayContentIconCenter" onClick={onHandleToLoginPageMaskConfirm}>
                            <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                        </div>

                        <div className="applyOverlayContentRowTitle">It is detected that you have already registered an account.</div>
                        <div className="applyOverlayContentRowTitle">Please login to your account through the login portal.</div>

                        <div className="homeApplyBtnLarge loginTopEdge" onClick={onHandleToLoginPageMaskConfirm}>
                            <div className="mainButtonGradient">OK</div>
                        </div>
                    </div>
                </div>
            </Mask>

            {/* 转注册页弹框 */}
            <Mask visible={needToRegisterPage} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="applyOverlayBg">
                    <div className="applyOverlayContent">
                        <div className="applyOverlayContentIconCenter" onClick={onHandleToRegisterPageMaskConfirm}>
                            <img className="applyOverlayIconCenter" src={icon_login_refuse} alt="" />
                        </div>

                        <div className="applyOverlayContentRowTitle">No account has been registered with this identity information.</div>
                        <div className="applyOverlayContentRowTitle">Please change your identity to log in or register a new account.</div>

                        <div className="homeApplyBtnLarge loginTopEdge" onClick={onHandleToRegisterPageMaskConfirm}>
                            <div className="mainButtonGradient">OK</div>
                        </div>
                    </div>
                </div>
            </Mask>

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>

            {/* {linkUrl &&
                <iframe
                    id="linkFrame"
                    src={linkUrl}
                    width="800"
                    height="600"
                    title="Link"
                    onLoad={onHandleUserLink}
                ></iframe>} */}
        </div>
    )
}